/* eslint-disable @typescript-eslint/no-unused-vars */
import React, { useState, useEffect, useCallback, useRef } from 'react';
import {
  Button,
  Table,
  Modal,
  Form,
  Input,
  message,
  Select,
  Divider,
  Pagination,
  Drawer,
  Tabs,
  Switch,
  TreeSelect,
  Space,
  Row,
  Col,
} from 'antd';
import {
  getDataPermissionRules,
  getDataPermissionRuleRoles,
  delDataPermissionRuleDistribution,
  getDataPermissionRuleUsers,
  delDataPermissionRule,
  addDataPermissionRuleDistribution,
  getDataPermissionResources,
  getDataPermissionRuleTypes,
  addDataPermissionRule,
  getDataPermissionResourceFields,
  getDataPermissionRule,
  modifyDataPermissionRule,
  getCorporateList,
  getSysUserInfo,
  getOrganizationNoPermission,
  getRoleListNoPermission,
  getUserListWithDataPermissionUser,
} from 'admin/servers/servers';
import { ColumnsType } from 'antd/lib/table';
import { FetchDataParam, FetchDataResponse, PageSelect } from 'components/UILibrary/pageSelect';
import { clearNull, verifyNull } from 'utils/tools';
import './style.scss';
import {
  AddDataPermissionRuleParams,
  DataPermissionField,
  DataPermissionResource,
  DataPermissionRuleInfo,
  DataPermissionRuleRole,
  DataPermissionRuleType,
  DataPermissionRuleUser,
  RuleParams,
  RuleParamsForQuery,
} from 'admin/schema/DataPermission';
import { MinusCircleOutlined, PlusOutlined, TeamOutlined } from '@ant-design/icons';
import { UserInfo } from 'admin/schema/User';
import { RoleInfo } from 'admin/schema/Role';

import { Rule } from 'antd/lib/form';
import { checkPermission } from 'permission/Index';
import { RuleItem } from './component/RuleItem';
import Tooltip from 'antd/es/tooltip';
import isNull from 'lodash/isNull';
import { cloneDeep, debounce } from 'lodash';
const Option = Select.Option;
const { TabPane } = Tabs;

const layout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 16 },
};

const OperationPermission: React.FC = () => {
  const [searchFormRef] = Form.useForm();
  const [ruleUserForm] = Form.useForm();
  const [ruleRoleForm] = Form.useForm();
  const [saveRuleForm] = Form.useForm();

  const isAdmin = useRef<boolean>(false);
  const [companySearchVisiable, setCompanySearchVisiable] = useState<boolean>(false);

  //新建/编辑规则类型
  const [mode, setMode] = useState('create');
  //数据表
  const [dataPermissionResourceList, setDataPermissionResourceList] = useState<
    DataPermissionResource[]
  >([]);
  //数据权限规则类型
  const [dataPermissionRuleTypeList, setDataPermissionRuleTypeList] = useState<
    DataPermissionRuleType[]
  >([]);
  const [organizationTreeData, setOrganizationTreeeData] = useState<[]>([]);
  const [organizationTreeDataVisible, setOrganizationTreeDataVisible] = useState(false);
  const [userListVisible, setUserListVisible] = useState(false);
  const [resourceFieldList, setResourceFieldList] = useState<DataPermissionField[]>([]);
  const dataPermissionFieldKey = useRef<string>('');
  const [advancedRule, setAdvancedRule] = useState<boolean>(false);

  // 当前页码
  const [current, setCurrent] = useState<number>(1);
  // 每页条数
  const [pageSize, setPageSize] = useState<number>(10);
  // 数据总数
  const [total, setTotal] = useState<number>(0);
  // Table loading状态
  const [tableLoading, setTableLoading] = useState<boolean>(false);
  // Table数据
  const [datePermissionRuleInfo, setDatePermissionRuleInfo] = useState<DataPermissionRuleInfo[]>(
    []
  );
  // 搜索内容
  const [ruleName, setRuleName] = useState<string>('');

  // 新建规则：弹框显示
  const [visible, setVisible] = useState(false);

  //赋权用户
  const [ruleUserVisible, setRuleUserVisible] = useState(false);
  // 当前页码
  const [ruleUserCurrent, setRuleUserCurrent] = useState<number>(1);
  // 每页条数
  const [ruleUserPageSize, setRuleUserPageSize] = useState<number>(5);
  // 数据总数
  const [ruleUserTotal, setRuleUserTotal] = useState<number>(0);
  // Table数据
  const [datePermissionRuleUser, setDatePermissionRuleUser] = useState<DataPermissionRuleUser[]>(
    []
  );
  // 用户数据列表
  const [userList, setUserList] = useState<UserInfo[]>([]);
  // 当前页码
  const userCurrent = useRef<number>(1);
  // 每页条数
  const [userPageSize, setUserPageSize] = useState<number>(6);
  // 数据总数
  const [userTotal, setUserTotal] = useState<number>(0);
  // 搜索内容
  const [userSearchText, setUserSearchText] = useState<string>('');

  //赋权角色
  const [ruleRoleVisible, setRuleRoleVisible] = useState(false);
  // 当前页码
  const [ruleRoleCurrent, setRuleRoleCurrent] = useState<number>(1);
  // 每页条数
  const [ruleRolePageSize, setRuleRolePageSize] = useState<number>(5);
  // 数据总数
  const [ruleRoleTotal, setRuleRoleTotal] = useState<number>(0);
  // Table数据
  const [datePermissionRuleRole, setDatePermissionRuleRole] = useState<DataPermissionRuleRole[]>(
    []
  );
  // 角色数据列表
  const [roleList, setRoleList] = useState<RoleInfo[]>([]);
  // 当前页码
  const roleCurrent = useRef<number>(1);
  // 每页条数
  const [rolePageSize, setRolePageSize] = useState<number>(6);
  // 数据总数
  const [roleTotal, setRoleTotal] = useState<number>(0);
  // 搜索内容
  const [roleSearchText, setRoleSearchText] = useState<string>('');

  //存储授权用户/角色时 选择的用户ID/角色ID列表
  const [ruleUserOrRoleList, setRuleUserOrRoleList] = useState<[]>([]);
  const ruleIdData = useRef<number>(0);
  const isSafeDelete = useRef<boolean>(false);
  const [defaultActiveKey, setDefaultActiveKey] = useState<string>('1');
  //规则编辑时,高级规则列表
  const [ruleParamsList, setRuleParamsList] = useState<RuleParamsForQuery[]>([]);
  const [hasChildrenVisible, setHasChildrenVisible] = useState<boolean>(false);
  const [overallSituationDisable, setOverallSituationDisable] = useState<boolean>(false);
  const [ruleTypeKey, setRuleTypeKey] = useState<string>('dataOrganization');

  /**
   * Table列描述数据对象
   */
  const renderScriptContent = (text: any, record: any, index: number) => {
    let showContent = '';
    if (!text || !text.length) {
      showContent = '';
    } else {
      showContent = text
        .map((item: any) => {
          return item;
        })
        .join(',');
    }
    const scripts: Array<string> = record.resourceNames || '';
    return (
      <Tooltip
        placement="topLeft"
        title={
          <>
            {scripts.length > 0 &&
              scripts?.map((item, num) => {
                return (
                  <div key={num}>
                    <div>数据表：{item}</div>
                  </div>
                );
              })}
            {!scripts && <div key={index}>数据表：{text}</div>}
          </>
        }
      >
        {showContent}
      </Tooltip>
    );
  };

  const columns: ColumnsType<DataPermissionRuleInfo> = [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      render: (text, record, index) => index + 1 + pageSize * (current - 1),
      width: 70,
    },
    {
      title: '规则名称',
      dataIndex: 'ruleName',
      key: 'ruleName',
    },
    {
      title: '数据源表',
      dataIndex: 'resourceNames',
      key: 'resourceNames',
      ellipsis: {
        showTitle: false,
      },
      render: renderScriptContent,
      // render(arr) {
      //   if (!arr || !arr.length) return '';
      //   return arr
      //     .map((item: any) => {
      //       return item;
      //     })
      //     .join(',');
      // },
    },
    {
      title: '授权规则',
      dataIndex: 'ruleContent',
      key: 'ruleContent',
    },
    {
      title: '操作',
      dataIndex: 'operation',
      key: 'operation',
      width: 320,
      render: (text, record, index) => {
        return (
          <>
            {checkPermission('/account/dataPermission/modify') && (
              <Button
                type="link"
                onClick={() => {
                  handleModify(record.ruleId);
                }}
              >
                编辑
              </Button>
            )}
            {checkPermission('/account/datapermission/rule/distribution') && (
              <Button
                type="link"
                disabled={record.overallSituation === 0}
                onClick={() => {
                  handleRuleUser(record);
                }}
              >
                赋权用户
              </Button>
            )}
            {checkPermission('/account/datapermission/rule/distribution') && (
              <Button
                type="link"
                disabled={record.overallSituation === 0}
                onClick={() => {
                  handleRuleRole(record);
                }}
              >
                赋权角色
              </Button>
            )}
            {checkPermission('/account/dataPermission/delete') && (
              <Button
                type="link"
                onClick={() => {
                  deleteDataPermissionRule(record);
                }}
              >
                删除
              </Button>
            )}
          </>
        );
      },
    },
  ];

  const ruleUserColumns: ColumnsType<DataPermissionRuleUser> = [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      render: (text, record, index) => index + 1 + ruleUserPageSize * (ruleUserCurrent - 1),
      width: 70,
    },
    {
      title: '用户名',
      dataIndex: 'nickName',
      key: 'nickName',
    },
    {
      title: '账号',
      dataIndex: 'userName',
      key: 'userName',
    },
    {
      title: '组织机构',
      dataIndex: 'organizationName',
      key: 'organizationName',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
    },
    {
      title: '操作',
      dataIndex: 'operation',
      key: 'operation',
      width: 100,
      render: (text, record, index) => {
        return (
          <>
            {checkPermission('/account/datapermission/rule/distribution/delete') && (
              <Button
                type="link"
                onClick={() => {
                  deleteRecordForRuleUser(record);
                }}
              >
                删除
              </Button>
            )}
          </>
        );
      },
    },
  ];

  const ruleRoleColumns: ColumnsType<DataPermissionRuleRole> = [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      render: (text, record, index) => index + 1 + ruleRolePageSize * (ruleRoleCurrent - 1),
      width: 70,
    },
    {
      title: '角色名',
      dataIndex: 'roleName',
      key: 'roleName',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
    },
    {
      title: '操作',
      dataIndex: 'operation',
      key: 'operation',
      width: 100,
      render: (text, record, index) => {
        return (
          <>
            {checkPermission('/account/datapermission/rule/distribution/delete') && (
              <Button
                type="link"
                onClick={() => {
                  deleteRecordForRuleRole(record);
                }}
              >
                删除
              </Button>
            )}
          </>
        );
      },
    },
  ];

  /**
   * Table数据加载
   */
  const initData = useCallback(async () => {
    setTableLoading(true);
    await getTableData();
    setTableLoading(false);

    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [current, pageSize, ruleName, dataPermissionFieldKey]);

  /**请求列表数据 */
  const getTableData = useCallback(async () => {
    try {
      const val = searchFormRef.getFieldsValue();
      console.log(val);
      if (isAdmin.current) {
        if (val.companyId == null || val.companyId === '' || val.companyId === undefined) {
          message.warn('请选择企业');
          return;
        }
      }
      const res = await getDataPermissionRules(
        clearNull({
          pageNo: current,
          pageSize: pageSize,
          ruleName: val.ruleName,
          companyId: val.companyId,
        })
      );
      setDatePermissionRuleInfo(res.data || []);
      setTotal(Number(res.count) || 0);
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
  }, [current, isAdmin, pageSize, searchFormRef]);

  /**
   * 获得登录用户信息
   */
  const determineIsAdmin = useCallback(async () => {
    getSysUserInfo()
      .then(res => {
        setCompanySearchVisiable(res.data.companyId === 0);
        isAdmin.current = res.data.companyId === 0;
        if (res.data.companyId !== 0) {
          initData();
        }
      })
      .catch(error => {
        console.error(`系统异常: ${JSON.stringify(error)}`);
      });
  }, [initData]);

  /**
   * 角色数据加载
   */
  const initRoles = useCallback(async () => {
    // setTableLoading(true);
    console.log(roleCurrent.current);
    console.log(rolePageSize);
    console.log(roleSearchText);
    try {
      const res = await getRoleListNoPermission({
        pageNo: roleCurrent.current,
        pageSize: rolePageSize,
        roleName: roleSearchText,
      });
      if (res.code === 0) {
        setRoleList(res.data || []);
        setRoleTotal(Number(res.count) || 1); // 备注：此处列表‘暂无数据’保留翻页数据，和其他地方处理方案不同，方便点击翻页，清空输入的搜索文字
        // console.log();
        // sessionStorage.setItem('intentionIdyitu', JSON.stringify(res.data));
      } else {
        message.error(`${res.tips}(错误码: ${res.code})`);
      }
      // console.log("initIntentions -> res", res);
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
    // setTableLoading(false);
  }, [roleCurrent, rolePageSize, roleSearchText]);

  /**
   * 用户数据加载
   */
  // const initUsers = useCallback(async () => {
  //   // setTableLoading(true);
  //   console.log(userCurrent.current);
  //   console.log(userPageSize);
  //   console.log(userSearchText);
  //   try {
  //     const res = await getUserList({
  //       pageNo: userCurrent.current,
  //       pageSize: userPageSize,
  //       userName: userSearchText,
  //     });
  //     if (res.code === 0) {
  //       setUserList(res.data || []);
  //       setUserTotal(Number(res.count) || 1); // 备注：此处列表‘暂无数据’保留翻页数据，和其他地方处理方案不同，方便点击翻页，清空输入的搜索文字
  //       // console.log();
  //       // sessionStorage.setItem('intentionIdyitu', JSON.stringify(res.data));
  //     } else {
  //       message.error(`${res.tips}(错误码: ${res.code})`);
  //     }
  //     // console.log("initIntentions -> res", res);
  //   } catch (error) {
  //     console.error(`系统异常: ${JSON.stringify(error)}`);
  //   }
  //   // setTableLoading(false);
  // }, [userCurrent, userPageSize, userSearchText]);

  /**
   * 用户数据加载
   */
  const initUsersNoPermission = useCallback(async () => {
    // setTableLoading(true);
    console.log(userCurrent.current);
    console.log(userPageSize);
    console.log(userSearchText);
    try {
      const res = await getUserListWithDataPermissionUser({
        pageNo: userCurrent.current,
        pageSize: userPageSize,
        userName: userSearchText,
      });
      if (res.code === 0) {
        setUserList(res.data || []);
        setUserTotal(Number(res.count) || 1); // 备注：此处列表‘暂无数据’保留翻页数据，和其他地方处理方案不同，方便点击翻页，清空输入的搜索文字
        // console.log();
        // sessionStorage.setItem('intentionIdyitu', JSON.stringify(res.data));
      } else {
        message.error(`${res.tips}(错误码: ${res.code})`);
      }
      // console.log("initIntentions -> res", res);
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
    // setTableLoading(false);
  }, [userCurrent, userPageSize, userSearchText]);

  /**请求列表数据 */
  const getDataPermissionRuleUserTableData = useCallback(async () => {
    try {
      console.log('ruleId:' + ruleIdData.current);
      const res = await getDataPermissionRuleUsers(ruleIdData.current, {
        pageNo: ruleUserCurrent,
        pageSize: ruleUserPageSize,
      });
      setDatePermissionRuleUser(res.data || []);
      setRuleUserTotal(Number(res.count) || 0);
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
  }, [ruleUserCurrent, ruleUserPageSize]);

  /**请求列表数据 */
  const getDataPermissionRuleRoleTableData = useCallback(async () => {
    try {
      const res = await getDataPermissionRuleRoles(ruleIdData.current, {
        pageNo: ruleRoleCurrent,
        pageSize: ruleRolePageSize,
      });
      setDatePermissionRuleRole(res.data || []);
      setRuleRoleTotal(Number(res.count) || 0);
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
  }, [ruleRoleCurrent, ruleRolePageSize]);

  // 数据初始化
  useEffect(() => {
    determineIsAdmin();
  }, [determineIsAdmin]);

  // 数据初始化
  useEffect(() => {
    initRoles();
  }, [initRoles]);

  // 数据初始化
  useEffect(() => {
    initUsersNoPermission();
  }, [initUsersNoPermission]);

  // 数据初始化
  useEffect(() => {
    getDataPermissionRuleUserTableData();
  }, [getDataPermissionRuleUserTableData]);

  // 数据初始化
  useEffect(() => {
    getDataPermissionRuleRoleTableData();
  }, [getDataPermissionRuleRoleTableData]);

  /**
   * 翻页
   * @param pageNo 点击页码
   */
  const onChagneCurrent = (pageNo: number) => {
    setCurrent(pageNo);
  };
  /**
   *改变每页显示条数
   * @param current 当前页码
   * @param pageSize 每页显示条数
   */
  const onChangePageSize = (current: number, pageSize: number) => {
    setPageSize(pageSize);
  };

  /**
   * 对table数据进行刷新：新增，编辑
   * @param pageNum 刷新页码
   */
  const refreshTable = async (pageNum?: number) => {
    if (pageNum) {
      current === pageNum ? initData() : setCurrent(pageNum);
    } else {
      initData();
    }
  };

  /**
   * 新增操作
   */
  const handleAdd = () => {
    saveRuleForm.resetFields();
    setMode('create');
    setResourceFieldList([]);
    setAdvancedRule(false);
    setRuleParamsList([]);
    setVisible(true);
    setOverallSituationDisable(false);
    setDefaultActiveKey('1');
    setOrganizationTreeDataVisible(false);
    setUserListVisible(false);
    setHasChildrenVisible(false);
    userCurrent.current = 1;
    fetchResourceList();
    fetchRuleTypeList();
    fetchOrganizationList();
    initUsersNoPermission();
  };

  /**
   * 编辑操作
   */
  const handleModify = (ruleId: number) => {
    setMode('modify');
    setVisible(true);
    setResourceFieldList([]);
    setOrganizationTreeDataVisible(false);
    setUserListVisible(false);
    setHasChildrenVisible(false);
    setOverallSituationDisable(true);
    ruleIdData.current = ruleId;
    userCurrent.current = 1;
    fetchResourceList();
    fetchRuleTypeList();
    fetchOrganizationList();
    initUsersNoPermission();
    getDataPermissionRule(ruleId)
      .then(res => {
        const data = res.data;
        if (!res.data) {
          return;
        }
        ruleTypeOnChange(data.ruleTypeKey);
        setAdvancedRule(data.ruleTypeKey === '-1' ? true : false);
        setDefaultActiveKey(data.ruleTypeKey === '-1' ? '2' : '1');
        setRuleParamsList([]);

        setHasChildrenVisible(data.ruleTypeKey === 'dataUser' ? false : true);

        const organizations: number[] = [];
        if (data.organizations) {
          data.organizations.forEach((item: any) => {
            organizations.push(item.organizationId);
          });
        }
        const userIds: any[] = [];
        if (data.users) {
          data.users.forEach((item: any) => {
            const obj = {
              value: item.userId,
              label: item.userName,
            };
            userIds.push(obj);
          });
        }

        const ruleParams = [] as any;
        if (data.ruleParams) {
          data.ruleParams?.map((item: any) => {
            const ruleParam = {} as RuleParams;
            ruleParam.fieldKey = item.fieldKey ? item.fieldKey : '';
            ruleParam.decisionSymbolKey = item.decisionSymbolKey ? item.decisionSymbolKey : '';
            ruleParam.fieldValue = item.fieldValue ? item.fieldValue : '';
            ruleParam.relationSymbol = item.relationSymbol ? item.relationSymbol : '';
            ruleParams.push(ruleParam);
          });
        }

        const fieldData = {
          ruleId: data.ruleId,
          ruleName: data.ruleName,
          ruleTypeKey: data.ruleTypeKey === '-1' ? '' : data.ruleTypeKey,
          overallSituation: data.overallSituation === 0 ? 1 : 0,
          resourceKeys: data.resourceKeys,
          hasChildren: data.hasChildren ? 1 : 0,
          organizationIds: organizations,
          userIds: userIds,
          ruleParams: ruleParams,
        };
        console.log(fieldData);

        if (data.ruleParams) {
          setRuleParamsList(data.ruleParams);
          console.log(ruleParamsList);
        }
        saveRuleForm.setFieldsValue(fieldData);

        if (data.resourceKeys) {
          fetchResourceFieldList(data.resourceKeys);
        }
      })
      .catch(error => {
        console.error(`系统异常: ${JSON.stringify(error)}`);
      });
  };

  //  分页配置项
  const pagination = {
    total: total,
    showTotal: (total: number) => `共 ${total} 条`,
    current: current,
    pageSize: pageSize,
    showSizeChanger: true,
    onChange: onChagneCurrent,
    onShowSizeChange: onChangePageSize,
  };

  //--------------------------------------------------------------------------赋权用户开始
  /**
   * 翻页
   * @param pageNo 点击页码
   */
  const onChagneRuleUserCurrent = (pageNo: number) => {
    setRuleUserCurrent(pageNo);
  };
  /**
   *改变每页显示条数
   * @param current 当前页码
   * @param pageSize 每页显示条数
   */
  const onChangeRuleUserPageSize = (current: number, pageSize: number) => {
    setRuleUserPageSize(pageSize);
  };
  //  分页配置项
  const ruleUserPagination = {
    total: ruleUserTotal,
    showTotal: (total: number) => `共 ${total} 条`,
    current: ruleUserCurrent,
    pageSize: ruleUserPageSize,
    showSizeChanger: true,
    onChange: onChagneRuleUserCurrent,
    onShowSizeChange: onChangeRuleUserPageSize,
  };

  /**
   * 授权用户操作
   * @param robotId
   */
  const handleRuleUser = useCallback(
    ({ ruleId }: DataPermissionRuleInfo) => {
      setRuleUserVisible(true);
      // setRuleId(ruleId);
      ruleIdData.current = ruleId;
      userCurrent.current = 1;
      setRuleUserCurrent(1);
      ruleUserForm.resetFields();
      setRuleUserOrRoleList([]);
      initUsersNoPermission();
      getDataPermissionRuleUserTableData();
    },
    [getDataPermissionRuleUserTableData, initUsersNoPermission, ruleUserForm]
  );

  /**
   * 取消用户数据权限
   */
  const deleteRecordForRuleUser = (record: DataPermissionRuleUser) => {
    Modal.confirm({
      content: '删除后无法恢复，确认删除吗',
      onOk: () => {
        delDataPermissionRuleDistribution({
          ruleId: ruleIdData.current,
          allocationType: 'user',
          allocationValues: [record.userId],
        })
          .then(res => {
            message.success('删除成功');
            getDataPermissionRuleUserTableData();
          })
          .catch(error => {
            console.error(`系统异常: ${JSON.stringify(error)}`);
          });
      },
    });
  };

  /**
   * 赋权用户/角色
   */
  const addRuleDistribution = useCallback(
    async (allocationType: 'user' | 'role') => {
      if (ruleUserOrRoleList.length === 0) {
        if (allocationType === 'user') {
          message.warn('请输入用户');
        } else {
          message.warn('请输入角色');
        }
        return;
      }
      try {
        await addDataPermissionRuleDistribution({
          ruleId: ruleIdData.current,
          allocationType: allocationType,
          allocationValues: ruleUserOrRoleList,
        })
          .then(res => {
            message.success('赋权成功');
            if (allocationType === 'user') {
              ruleUserForm.resetFields();
              getDataPermissionRuleUserTableData();
            } else {
              ruleRoleForm.resetFields();
              getDataPermissionRuleRoleTableData();
            }
          })
          .catch(error => {
            console.error(`系统异常: ${JSON.stringify(error)}`);
          });
      } catch (error) {
        console.error(`系统异常: ${JSON.stringify(error)}`);
      }
    },
    [
      getDataPermissionRuleRoleTableData,
      getDataPermissionRuleUserTableData,
      ruleRoleForm,
      ruleUserForm,
      ruleUserOrRoleList,
    ]
  );

  //--------------------------------------------------------------------------赋权用户结束

  //--------------------------------------------------------------------------赋权角色开始
  /**
   * 翻页
   * @param pageNo 点击页码
   */
  const onChagneRuleRoleCurrent = (pageNo: number) => {
    setRuleRoleCurrent(pageNo);
  };
  /**
   *改变每页显示条数
   * @param current 当前页码
   * @param pageSize 每页显示条数
   */
  const onChangeRuleRolePageSize = (current: number, pageSize: number) => {
    setRuleRolePageSize(pageSize);
  };
  //  分页配置项
  const ruleRolePagination = {
    total: ruleRoleTotal,
    showTotal: (total: number) => `共 ${total} 条`,
    current: ruleRoleCurrent,
    pageSize: ruleRolePageSize,
    showSizeChanger: true,
    onChange: onChagneRuleRoleCurrent,
    onShowSizeChange: onChangeRuleRolePageSize,
  };

  /**
   * 授权角色操作
   * @param robotId
   */
  const handleRuleRole = ({ ruleId }: DataPermissionRuleInfo) => {
    setRuleRoleVisible(true);
    // setRuleId(ruleId);
    ruleIdData.current = ruleId;
    roleCurrent.current = 1;
    setRuleRoleCurrent(1);
    ruleRoleForm.resetFields;
    setRuleUserOrRoleList([]);
    initRoles();
    getDataPermissionRuleRoleTableData();
  };

  /**
   * 取消角色数据权限
   */
  const deleteRecordForRuleRole = (record: DataPermissionRuleRole) => {
    Modal.confirm({
      content: '删除后无法恢复，确认删除吗',
      onOk: () => {
        delDataPermissionRuleDistribution({
          ruleId: ruleIdData.current,
          allocationType: 'role',
          allocationValues: [record.roleId],
        })
          .then(res => {
            message.success('删除成功');
            getDataPermissionRuleRoleTableData();
          })
          .catch(error => {
            console.error(`系统异常: ${JSON.stringify(error)}`);
          });
      },
    });
  };

  //--------------------------------------------------------------------------赋权角色结束

  //--------------------------------------------------------------------------删除数据权限规则开始
  const deleteDataPermissionRule = (record: DataPermissionRuleInfo) => {
    isSafeDelete.current = false;
    Modal.confirm({
      content: (
        <>
          <p>删除后无法恢复，确认删除吗?</p>
          使用安全策略
          <Switch
            onChange={value => {
              isSafeDelete.current = value;
              console.log(isSafeDelete.current);
            }}
          />
        </>
      ),
      onOk: () => {
        delDataPermissionRule(record.ruleId as number, {
          isSafeDelete: isSafeDelete.current,
        })
          .then(res => {
            message.success('删除成功');
            refreshTable(1);
          })
          .catch(error => {
            console.error(`系统异常: ${JSON.stringify(error)}`);
          });
      },
    });
  };
  //--------------------------------------------------------------------------删除数据权限规则结束

  const fetchCompany = (arg: FetchDataParam): FetchDataResponse => {
    return new Promise(resolve => {
      getCorporateList({
        pageNo: arg.pageNum,
        pageSize: arg.pageSize,
        companyName: '',
      })
        .then(res => {
          if (!res.data) {
            resolve({
              data: [],
              total: 1,
            });
            return;
          }
          resolve({
            data: res.data?.map(item => {
              return {
                label: item.companyName,
                value: item.companyId ? item.companyId.toString() : '',
              };
            }),
            total: res.count as number,
          });
        })
        .catch(error => {
          console.error(`系统异常: ${JSON.stringify(error)}`);
        });
    });
  };

  /**
   * 获取数据表列表
   */
  const fetchResourceList = () => {
    getDataPermissionResources()
      .then(res => {
        setDataPermissionResourceList(res.data);
      })
      .catch(error => {
        console.error(`系统异常: ${JSON.stringify(error)}`);
      });
  };

  /**
   * 获取数据规则类型列表
   */
  const fetchRuleTypeList = () => {
    getDataPermissionRuleTypes()
      .then(res => {
        setDataPermissionRuleTypeList(res.data);
      })
      .catch(error => {
        console.error(`系统异常: ${JSON.stringify(error)}`);
      });
  };

  /**
   *
   * 获取组织结构列表的函数
   */
  const fetchOrganizationList = () => {
    getOrganizationNoPermission()
      .then(res => {
        if (!res.data) {
          return;
        }
        const treeData = JSON.parse(
          JSON.stringify(res.data)
            .replace(/organizationId/g, 'value')
            .replace(/organizationName/g, 'title')
            .replace(/subOrganizations/g, 'children')
        );
        const addIcon = (item: any) => {
          !item.children && (item.switcherIcon = <TeamOutlined />);
          if (item.children) {
            item.children.forEach((child: any) => {
              addIcon(child);
            });
          }
        };
        addIcon(treeData[0]);
        console.log(treeData);
        setOrganizationTreeeData(treeData);
      })
      .catch(error => {
        console.error(`系统异常: ${JSON.stringify(error)}`);
      });
  };

  const fetchResourceFieldList = (value: any) => {
    if (isNull(value) || value.length === 0) {
      setResourceFieldList([]);
      return;
    }
    getDataPermissionResourceFields(value)
      .then(res => {
        setResourceFieldList(res.data);
      })
      .catch(error => {
        console.error(`系统异常: ${JSON.stringify(error)}`);
      });
  };

  const clearRuleParamsItem = () => {
    const val = saveRuleForm.getFieldsValue();
    let ruleParams = [] as any;
    if (val.ruleParams) {
      val.ruleParams?.map((item: any) => {
        const ruleParam = {} as RuleParams;
        ruleParam.fieldKey = null;
        ruleParam.decisionSymbolKey = null;
        ruleParam.fieldValue = null;
        ruleParam.relationSymbol = null;
        ruleParams.push(ruleParam);
      });
    } else {
      ruleParams = [{ fieldValue: '' }];
    }
    saveRuleForm.setFieldsValue({
      ruleParams: ruleParams,
    });
  };

  const buildFooter = () => {
    return (
      <div className="drawer-footer-buttongroup">
        <Button
          type="primary"
          onClick={() => {
            submitData();
          }}
        >
          确定
        </Button>
        <Button
          onClick={() => {
            close();
          }}
        >
          取消
        </Button>
      </div>
    );
  };

  /**获取校验规则 */
  const getRules = (key: string, message?: string): Rule[] => {
    const ruleMap = new Map();
    ruleMap.set('ruleName', verifyNull(message));
    ruleMap.set('overallSituation', verifyNull(message));
    ruleMap.set('resourceKeys', verifyNull(message));
    ruleMap.set('overallSituation', verifyNull(message));

    if (!advancedRule) {
      ruleMap.set('ruleTypeKey', verifyNull(message));
      if (ruleTypeKey === 'dataOrganization') {
        ruleMap.set('organizationIds', verifyNull(message));
      } else if (ruleTypeKey === 'dataUser') {
        ruleMap.set('userIds', verifyNull(message));
      }
    } else {
      ruleMap.set('fieldKey', verifyNull(message));
      ruleMap.set('relationSymbol', verifyNull(message));
      ruleMap.set('fieldValue', verifyNull(message));
      ruleMap.set('decisionSymbolKey', verifyNull(message));
    }

    return ruleMap.get(key);
  };

  /** 提交（新建/编辑）的数据 */
  const submitData = () => {
    const form = saveRuleForm;
    form?.validateFields().then(res => {
      const val = form.getFieldsValue();
      console.log(val);
      const userIds: number[] = [];
      if (val.userIds) {
        val.userIds.forEach((item: any) => {
          userIds.push(item.value);
        });
      }
      const ruleParams: RuleParams[] = [];
      if (val.ruleParams) {
        val.ruleParams?.map((item: any) => {
          const ruleParam = {} as RuleParams;
          ruleParam.fieldKey = item.fieldKey ? item.fieldKey : '';
          ruleParam.decisionSymbolKey = item.decisionSymbolKey ? item.decisionSymbolKey : '';
          ruleParam.fieldValue = item.fieldValue ? item.fieldValue : '';
          ruleParam.relationSymbol = item.relationSymbol ? item.relationSymbol : '';
          ruleParams.push(ruleParam);
        });
      }

      const addParams: AddDataPermissionRuleParams = {
        ruleName: '',
        ruleTypeKey: '',
        resourceKeys: [],
      };

      addParams.ruleName = val.ruleName;
      addParams.ruleTypeKey = advancedRule ? '-1' : val.ruleTypeKey;
      addParams.resourceKeys = val.resourceKeys;
      if (advancedRule) {
        if (containDuplicate(ruleParams, 'fieldKey')) {
          message.warn('高级规则中不能存在相同的属性字段');
          return;
        }

        addParams.ruleParams = ruleParams;
      } else {
        addParams.organizationIds = val.organizationIds;
        addParams.userIds = userIds;
        if (val.ruleTypeKey !== 'dataUser') {
          addParams.hasChildren = val.hasChildren;
        }
      }

      if (mode === 'create') {
        addParams.overallSituation = val.overallSituation ? 0 : 1;
        addDataPermissionRule(addParams)
          .then(res => {
            message.success('新增成功');
            close();
            initData();
          })
          .catch(error => {
            console.error(`系统异常: ${JSON.stringify(error)}`);
          });
      } else {
        modifyDataPermissionRule(ruleIdData.current, addParams)
          .then(res => {
            message.success('修改成功');
            close();
            initData();
          })
          .catch(error => {
            console.error(`系统异常: ${JSON.stringify(error)}`);
          });
      }
    });
  };

  const containDuplicate = (arr: any, prop: any) =>
    arr.reduce((m: any, x: any) => m.set(x[prop], x), new Map()).size !== arr.length;

  /**
   * 关闭抽屉
   */
  const close = () => {
    setVisible(false);
    saveRuleForm.resetFields();
    //this.roleSelectRef.current?.clear();
  };

  const ruleTypeOnChange = (value: any) => {
    console.log('规则类型:' + value);
    if (value === 'dataOrganization') {
      setOrganizationTreeDataVisible(true);
      setUserListVisible(false);
    } else if (value === 'dataUser') {
      setOrganizationTreeDataVisible(false);
      setUserListVisible(true);
    } else {
      setOrganizationTreeDataVisible(false);
      setUserListVisible(false);
    }
  };

  return (
    <>
      <div className="mgr-header permission-task-list-header">
        <div className="mgr-header-left">
          <Form form={searchFormRef}>
            <Row gutter={24}>
              {companySearchVisiable ? (
                <Col md={12} xl={8} xxl={5}>
                  <Form.Item label="企业" name="companyId">
                    <PageSelect allowClear placeholder="请选择企业" fetchData={fetchCompany} />
                  </Form.Item>
                </Col>
              ) : (
                ''
              )}
              <Col md={12} xl={8} xxl={5}>
                <Form.Item label="规则名称" name="ruleName">
                  <Input placeholder="请输入规则名称" />
                </Form.Item>
              </Col>
              <Col md={12} xl={8} xxl={5}>
                <Button
                  type="primary"
                  onClick={() => {
                    initData();
                  }}
                >
                  搜索
                </Button>
              </Col>
            </Row>
          </Form>
        </div>
        <div className="mgr-header-right">
          <div className="robot-button-container">
            {checkPermission('/account/dataPermission/add') && (
              <Button
                type="primary"
                onClick={() => {
                  handleAdd();
                }}
              >
                新建规则
              </Button>
            )}
          </div>
        </div>
      </div>
      <div className="mgr-table robots-list">
        <Table
          scroll={{ x: '100%', scrollToFirstRowOnChange: true }}
          loading={tableLoading}
          columns={columns}
          dataSource={datePermissionRuleInfo}
          rowKey="ruleId"
          pagination={pagination}
        />
      </div>
      <Drawer
        width={940}
        visible={visible}
        className="user-operation-drawer"
        title={mode === 'create' ? '新建规则' : '编辑规则'}
        onClose={() => {
          close();
        }}
        footer={buildFooter()}
      >
        <Form
          {...layout}
          layout="horizontal"
          form={saveRuleForm}
          initialValues={{
            hasChildren: true,
            overallSituation: false,
            ruleParams: [{ fieldValue: '' }],
          }}
        >
          <Form.Item
            label="规则名称"
            name="ruleName"
            rules={getRules('ruleName', '请输入50位内字符')}
            getValueFromEvent={event => {
              return event.target.value.replace(/\s+/g, '');
            }}
          >
            <Input maxLength={50} placeholder="请输入规则名称" />
          </Form.Item>
          <Form.Item
            label="数据表"
            name="resourceKeys"
            rules={getRules('resourceKeys', '请选择需要分配的数据表')}
          >
            <Select
              showSearch={false}
              mode="multiple"
              style={{ width: '100%' }}
              placeholder="请选择需要分配的数据表"
              onChange={(value: any) => {
                console.log(value);
                fetchResourceFieldList(value);
                clearRuleParamsItem();
                // resourceKeys.current = value;
              }}
            >
              {dataPermissionResourceList?.map(item => {
                return (
                  <Option key={item.resourceKey} value={item.resourceKey}>
                    {item.resourceName}
                  </Option>
                );
              })}
            </Select>
          </Form.Item>
          <Form.Item
            className="a2"
            label="企业全局赋权"
            name="overallSituation"
            valuePropName="checked"
            rules={
              overallSituationDisable
                ? [{ required: false }]
                : getRules('overallSituation', '请选择企业全局赋权')
            }
          >
            <Switch defaultChecked disabled={overallSituationDisable} />
          </Form.Item>
          {/* <Form.Item label="数据授权规则" name="size">
                <Radio.Group>
                  <Radio.Button value="简单规则">简单规则</Radio.Button>
                  <Radio.Button value="高级规则">高级规则</Radio.Button>
                </Radio.Group>
              </Form.Item> */}
          <Form.Item
            label="数据授权规则"
            //rules={getRules('resourceKeys', '请选择')}
          >
            <Tabs
              defaultActiveKey={defaultActiveKey}
              activeKey={defaultActiveKey}
              style={{ marginTop: -8 }}
              onChange={value => {
                setDefaultActiveKey(value);
                if (value === '2') {
                  setAdvancedRule(true);
                  saveRuleForm.setFieldsValue({
                    ruleParams: [{ fieldValue: '' }],
                  });
                } else {
                  setAdvancedRule(false);
                }
              }}
            >
              <TabPane tab="简单规则" key="1">
                <Form.Item name="ruleTypeKey" rules={getRules('ruleTypeKey', '请选择规则类型')}>
                  <Select
                    style={{ width: '100%' }}
                    placeholder="请选择规则类型"
                    onChange={value => {
                      setRuleTypeKey(value as string);
                      ruleTypeOnChange(value);
                      setHasChildrenVisible(value === 'dataUser' ? false : true);
                    }}
                  >
                    {dataPermissionRuleTypeList?.map(item => {
                      return (
                        <Option key={item.typeKey} value={item.typeKey}>
                          {item.typeName}
                        </Option>
                      );
                    })}
                  </Select>
                </Form.Item>
                {organizationTreeDataVisible ? (
                  <Form.Item
                    name="organizationIds"
                    rules={getRules('organizationIds', '请选择规则类型')}
                  >
                    <TreeSelect
                      showSearch
                      style={{ width: '100%' }}
                      //value={this.state.value}
                      dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                      placeholder="获取指定组织数据"
                      allowClear
                      multiple
                      treeNodeFilterProp="title"
                      treeDefaultExpandAll
                      treeData={organizationTreeData}
                      //onChange={this.onChange}
                    ></TreeSelect>
                  </Form.Item>
                ) : (
                  ''
                )}
                {userListVisible ? (
                  <Form.Item name="userIds" rules={getRules('userIds', '请选择规则类型')}>
                    <Select
                      mode="multiple"
                      style={{ width: '100%' }}
                      showSearch
                      labelInValue
                      allowClear
                      placeholder="请选择用户"
                      // getPopupContainer={triggerNode => triggerNode.parentElement}
                      // onDeselect={(item: any) => {
                      //   onRemoveLink('fromPort', item.label, selectedData.key);
                      // }}
                      onBlur={() => {
                        // 失焦后设置搜索内容空白, 定时器-避免添加意图时找不到搜索内容
                        setTimeout(() => {
                          setUserSearchText('');
                        }, 500);
                      }}
                      onSearch={text => {
                        userCurrent.current = 1;
                        setUserSearchText(text.trim());
                      }}
                      filterOption={false}
                      onChange={(obj: any, options) => {
                        console.log('用户-> value', obj);
                        /**修改属性名 */
                        const newObj = cloneDeep(obj).map((item: any) => {
                          return item.key;
                        });
                        setRuleUserOrRoleList(newObj);
                      }}
                      /**自定义下拉区域 */
                      dropdownRender={menu => (
                        <div>
                          {menu}
                          <Divider style={{ margin: '4px 0' }} />
                          <div style={{ padding: '8px', textAlign: 'center' }}>
                            <Pagination
                              simple
                              current={userCurrent.current}
                              total={userTotal}
                              pageSize={userPageSize}
                              onChange={current => {
                                userCurrent.current = current;
                                initUsersNoPermission();
                              }}
                            />
                          </div>
                          <Divider style={{ margin: '4px 0' }} />
                        </div>
                      )}
                    >
                      {/* 意图列表-select选项option */}
                      {userList?.map(item => {
                        return (
                          <Option key={item.userId} value={item.userId}>
                            {item.nickName}
                          </Option>
                        );
                      })}
                    </Select>
                  </Form.Item>
                ) : (
                  ''
                )}
                {hasChildrenVisible ? (
                  <Form.Item
                    className="a2"
                    label="获取子组织数据"
                    name="hasChildren"
                    valuePropName="checked"
                  >
                    <Switch defaultChecked />
                  </Form.Item>
                ) : (
                  ''
                )}
              </TabPane>
              <TabPane tab="高级规则" key="2">
                <Form.List name="ruleParams">
                  {(fields, { add, remove }) => (
                    <>
                      {fields.map(({ key, name, fieldKey, ...restField }) => (
                        <Space
                          key={key}
                          style={{ display: 'flex', marginBottom: 8 }}
                          align="baseline"
                        >
                          <RuleItem
                            name={name}
                            resourceFieldList={resourceFieldList}
                            ruleParamsList={ruleParamsList}
                            advancedRule={advancedRule}
                            ruleForm={saveRuleForm}
                          ></RuleItem>
                          {name > 0 ? (
                            <MinusCircleOutlined
                              onClick={() => {
                                remove(name);
                              }}
                            />
                          ) : (
                            ''
                          )}
                        </Space>
                      ))}
                      <Form.Item>
                        <Button
                          type="dashed"
                          onClick={() => {
                            add();
                          }}
                          block
                          icon={<PlusOutlined />}
                        >
                          添加条件表达式
                        </Button>
                      </Form.Item>
                    </>
                  )}
                </Form.List>
                {/* </div> */}
              </TabPane>
            </Tabs>
          </Form.Item>
        </Form>
      </Drawer>
      {/* 赋权用户 */}
      <Modal
        title="赋权用户"
        centered
        width={800}
        footer={null}
        maskClosable={false}
        visible={ruleUserVisible}
        onCancel={() => {
          setRuleUserVisible(false);
        }}
        destroyOnClose={true}
      >
        <div className="mgr-header">
          <div className="mgr-header-left">
            <Form form={ruleUserForm}>
              <Form.Item>
                <Select
                  mode="multiple"
                  style={{ width: 400 }}
                  showSearch
                  labelInValue
                  allowClear
                  placeholder="请输入用户名/账号再赋权"
                  // getPopupContainer={triggerNode => triggerNode.parentElement}
                  // onDeselect={(item: any) => {
                  //   onRemoveLink('fromPort', item.label, selectedData.key);
                  // }}
                  onBlur={() => {
                    // 失焦后设置搜索内容空白, 定时器-避免添加意图时找不到搜索内容
                    setTimeout(() => {
                      setUserSearchText('');
                    }, 500);
                  }}
                  onSearch={debounce(text => {
                    userCurrent.current = 1;
                    setUserSearchText(text.trim());
                  }, 700)}
                  filterOption={false}
                  onChange={(obj: any, options) => {
                    console.log('用户-> value', obj);
                    /**修改属性名 */
                    const newObj = cloneDeep(obj).map((item: any) => {
                      return item.key;
                    });
                    setRuleUserOrRoleList(newObj);
                  }}
                  /**自定义下拉区域 */
                  dropdownRender={menu => (
                    <div>
                      {menu}
                      <Divider style={{ margin: '4px 0' }} />
                      <div style={{ padding: '8px', textAlign: 'center' }}>
                        <Pagination
                          simple
                          current={userCurrent.current}
                          total={userTotal}
                          pageSize={userPageSize}
                          onChange={current => {
                            userCurrent.current = current;
                            initUsersNoPermission();
                          }}
                        />
                      </div>
                      <Divider style={{ margin: '4px 0' }} />
                    </div>
                  )}
                >
                  {/* 意图列表-select选项option */}
                  {userList?.map(item => {
                    return (
                      <Option key={item.userId} value={item.userId}>
                        {item.nickName}
                      </Option>
                    );
                  })}
                </Select>
                <Button
                  type="primary"
                  style={{
                    marginLeft: 10,
                  }}
                  onClick={() => addRuleDistribution('user')}
                >
                  赋权
                </Button>
              </Form.Item>
            </Form>
          </div>
        </div>
        <div className="mgr-table">
          <h4>已赋权用户</h4>
          <Table
            scroll={{ x: '100%', scrollToFirstRowOnChange: true }}
            loading={tableLoading}
            columns={ruleUserColumns}
            dataSource={datePermissionRuleUser}
            rowKey="userId"
            pagination={ruleUserPagination}
          />
        </div>
      </Modal>
      {/* 赋权角色 */}
      <Modal
        title="赋权角色"
        centered
        width={800}
        footer={null}
        maskClosable={false}
        visible={ruleRoleVisible}
        onCancel={() => {
          setRuleRoleVisible(false);
        }}
        destroyOnClose={true}
      >
        <div className="mgr-header">
          <div className="mgr-header-left">
            <Form form={ruleRoleForm}>
              <Form.Item>
                <Select
                  mode="multiple"
                  style={{ width: 400 }}
                  showSearch
                  labelInValue
                  allowClear
                  placeholder="请输入角色名再赋权"
                  //getPopupContainer={triggerNode => triggerNode.parentElement}
                  // onDeselect={(item: any) => {
                  //   onRemoveLink('fromPort', item.label, selectedData.key);
                  // }}
                  onBlur={() => {
                    // 失焦后设置搜索内容空白, 定时器-避免添加意图时找不到搜索内容
                    setTimeout(() => {
                      setRoleSearchText('');
                    }, 500);
                  }}
                  onSearch={debounce(text => {
                    roleCurrent.current = 1;
                    setRoleSearchText(text.trim());
                  }, 700)}
                  // onSearch={text => {
                  //   roleCurrent.current = 1;
                  //   setRoleSearchText(text.trim());
                  // }}
                  filterOption={false}
                  onChange={(obj: any, options) => {
                    console.log('用户-> value', obj);
                    /**修改属性名 */
                    const newObj = cloneDeep(obj).map((item: any) => {
                      return item.key;
                    });
                    setRuleUserOrRoleList(newObj);
                  }}
                  /**自定义下拉区域 */
                  dropdownRender={menu => (
                    <div>
                      {menu}
                      <Divider style={{ margin: '4px 0' }} />
                      <div style={{ padding: '8px', textAlign: 'center' }}>
                        <Pagination
                          simple
                          current={roleCurrent.current}
                          total={roleTotal}
                          pageSize={rolePageSize}
                          onChange={current => {
                            roleCurrent.current = current;
                            initRoles();
                          }}
                        />
                      </div>
                      <Divider style={{ margin: '4px 0' }} />
                    </div>
                  )}
                >
                  {/* 意图列表-select选项option */}
                  {roleList?.map(item => {
                    return (
                      <Option key={item.roleId} value={item.roleId}>
                        {item.roleName}
                      </Option>
                    );
                  })}
                </Select>
                <Button
                  type="primary"
                  style={{
                    marginLeft: 10,
                  }}
                  onClick={() => addRuleDistribution('role')}
                >
                  赋权
                </Button>
              </Form.Item>
            </Form>
          </div>
        </div>
        <div className="mgr-table">
          <h4>已赋权角色</h4>
          <Table
            scroll={{ x: '100%', scrollToFirstRowOnChange: true }}
            loading={tableLoading}
            columns={ruleRoleColumns}
            dataSource={datePermissionRuleRole}
            rowKey="roleId"
            pagination={ruleRolePagination}
          />
        </div>
      </Modal>
    </>
  );
};

export default OperationPermission;
